import { Tools } from "../utils/Tools";
import { HelloCmd } from "./CmdData";
import CmdMgr from "./CmdMgr";
import HandleMgr from "./HandleMgr";



export default class WebSocketManager {

    private static _instance: WebSocketManager;

    public static instance(): WebSocketManager {
        if (!WebSocketManager._instance) {
            WebSocketManager._instance = new WebSocketManager;
        }
        return WebSocketManager._instance;
    }



    private socket: Laya.Socket;

    public connectServer(host: string) {
        if (this.socket) {
            this.socket.close();
        }

        this.socket = new Laya.Socket;
        this.socket.endian = Laya.Byte.BIG_ENDIAN;
        this.socket.connectByUrl(host);
        this.socket.on(Laya.Event.OPEN, this, this.openHandler);
        this.socket.on(Laya.Event.MESSAGE, this, this.receiveHandler);
        this.socket.on(Laya.Event.CLOSE, this, this.closeHandler);
        this.socket.on(Laya.Event.ERROR, this, this.errorHandler);
    }


    private openHandler(event: any = null): void {
        console.log("Websocket连接打开", Tools.formatDate());
        let data = { name: "小强" }
        let msg: gameMsg.IMyExternalMessage = {
            cmdCode: HelloCmd.Cmd,
            protocolSwitch: 0,
            cmdMerge: CmdMgr.getMergeCmd(HelloCmd.Cmd, HelloCmd.Sub_Here),
            responseStatus: 0,
            validMsg: "",
            dataContent: gameMsg.HelloReq.encode(data).finish()
        }


        this.send(gameMsg.MyExternalMessage.encode(msg).finish())
    }


    private receiveHandler(msg: any = null): void {
        let byte: Laya.Byte = new Laya.Byte;
        byte.writeArrayBuffer(msg);
        let data: gameMsg.MyExternalMessage = gameMsg.MyExternalMessage.decode(byte.getUint8Array(0, byte.length))
        if (data.responseStatus != 0) {
            console.warn("错误码:", data.responseStatus)
            //todo错误码处理
        } else {
            console.log("状态码:", data.responseStatus)
            HandleMgr.packageHandler(CmdMgr.getCmd(data.cmdMerge), CmdMgr.getSubCmd(data.cmdMerge), data.dataContent);
        }


    }

    private closeHandler(event: any = null): void {
        console.log("Websocket连接关闭", Tools.formatDate());
        clearInterval(this.intervalId);
    }

    private errorHandler(event: any = null): void {
        console.log("Websocket传输错误:%s", Tools.formatDate());
    }

    private intervalId;
    public missHeartNum: number = 0;
    private sendPong() {

        this.intervalId = setInterval(() => {
            if (this.socket) {
                this.missHeartNum++;
                if (this.missHeartNum >= 12) {
                    this.clearSock();
                    clearInterval(this.intervalId);
                    return;
                }
            }
        }, 5000);
    }

    public clearSock(): void {
        if (this.socket) {
            this.socket.close();
            this.socket = null;
        }
    }


    public map: Object = {};


    //发送消息
    public send(pbBuff: Uint8Array): void {
        if (this.socket && this.socket.connected) {
            if (!pbBuff) {
                return;
            }
            this.socket.send(pbBuff);
        } else {
            //网络连接异常
            // this.connect();
        }
    }

}